package com.cg.design.graphicdesignpattern.interpreter.language;

import java.util.ArrayList;

/**
 * 对应<command list>标签的类，继承了BaseNode类
 *
 * @program: LeetCode->CommandListNode
 * @author: cg
 * @create: 2022-04-06 08:41
 **/
public class CommandListNode extends BaseNode {

    /**
     * 保存与<command>对应的CommandNode类的实例
     */
    private final ArrayList<BaseNode> list = new ArrayList<>();

    @Override
    public void parse(Context context) throws ParseException {
        while (true) {
            if (context.currentToken() == null) {
                throw new ParseException("Missing 'end'");
            } else if ("end".equals(context.currentToken())) {
                context.skipToken("end");
                break;
            } else {
                BaseNode commandNode = new CommandNode();
                commandNode.parse(context);
                list.add(commandNode);
            }
        }
    }

    @Override
    public void execute() throws ExecuteException {
        for (BaseNode baseNode : list) {
            baseNode.execute();
        }
    }

    @Override
    public String toString() {
        return list.toString();
    }
}
